<?php
class UsuariosController extends AppController {

    public $components = array('Crop');

	public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow(array('login', 'logout', 'crop', 'getImage'));
	}

    public function index() {
        $this->set('usuarios', $this->Usuario->find('all'));
    }

    public function view($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Usuário inválido'));
        }

        $usuario = $this->Usuario->findById($id);
        if (!$usuario) {
            throw new NotFoundException(__('Usuário inválido'));
        }
        $this->set('usuario', $usuario);
    }

    public function add() {
        if ($this->request->is('post')) {
            $this->Usuario->create();
            if ($this->Usuario->save($this->request->data)) {
				$this->Session->setFlash('<a class="close"></a><p>O usuário foi salvo.</p>', 'default', array('escape' => false, 'class' => 'notibar msgsuccess'));
				$errorUpload = $this->request->data["Usuario"]["photo"]["error"];
				if ($errorUpload == 0){
					print_r($errorUpload);
					$this->redirect(array('action' => 'crop', $this->Usuario->id));
				} else {
					$this->redirect(array('action' => 'view', $this->Usuario->id));
				}
            }
        }

		$this->set('perfis', $this->Usuario->Perfil->find('list'));
		$this->set('errors', $this->Usuario->validationErrors);
    }

    public function edit($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Usuário inválido'));
        }

        $usuario = $this->Usuario->findById($id);
        if (!$usuario) {
            throw new NotFoundException(__('usuario'));
        }

        $usuario['Usuario']['password'] = "";

        if ($this->request->is('post') || $this->request->is('put')) {
            $this->Usuario->id = $id;

			$fields = array_keys($this->Usuario->schema());
			if ($this->request->data["Usuario"]["password"] == "" and $this->request->data["Usuario"]["password2"] == ""){
				$blackList = array('password', 'password2');
				$fields = array_diff($fields, $blackList);
			}

            if ($this->Usuario->save($this->data, true, $fields)){
				$this->Session->setFlash('<a class="close"></a><p>O usuário foi salvo.</p>', 'default', array('escape' => false, 'class' => 'notibar msgsuccess'));
				$errorUpload = $this->request->data["Usuario"]["photo"]["error"];
				if ($errorUpload == 0){
					print_r($errorUpload);
					$this->redirect(array('action' => 'crop', $this->Usuario->id));
				} else {
					$this->redirect(array('action' => 'view', $this->Usuario->id));
				}
            }
        }

        if (!$this->request->data) {
            $this->request->data = $usuario;
        }

		$this->set('perfis', $this->Usuario->Perfil->find('list'));
		$this->set('errors', $this->Usuario->validationErrors);
		$this->set('usuario', $usuario);
    }

    public function conta() {
		$usuario = $this->Usuario->findById($this->Auth->User('id'));
        if (!$usuario) {
            throw new NotFoundException(__('usuario'));
        }

		$usuario['Usuario']['password'] = "";

        if ($this->request->is('post') || $this->request->is('put')) {
            $this->Usuario->id = $usuario["Usuario"]["id"];

			$username = $this->request->data["Usuario"]["username"];
			$password = $this->request->data["Usuario"]["password"];
			$password2 = $this->request->data["Usuario"]["password2"];

			$fields = array('username','password','password2');

            if ($this->Usuario->save(array('Usuario' => array('username'=> $username,'password' => $password, 'password2' => $password2)), true, $fields)) {
				$this->layout = 'ajax';
				$this->autoRender = false;
				echo json_encode(true);
            }
        }

        if (!$this->request->data) {
            $this->request->data = $usuario;
        }

		$this->set('errors', $this->Usuario->validationErrors);
	}

    public function delete($id) {
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }
		
		$usuario_logado = $this->Usuario->findById($this->Auth->User('id'));

		if ($usuario_logado["Usuario"]["id"] == $id) {
			$this->Session->setFlash('<a class="close"></a><p>Não é possível deletar o usuário logado.</p>', 'default', array('escape' => false, 'class' => 'notibar msgerror'));

            $this->redirect(array('action' => 'index'));
		} else {
			print_r($usuario_logado);
		}

        if ($this->Usuario->delete($id)) {
			$this->Session->setFlash('<a class="close"></a><p>O usuário com o id: ' . $id . ' foi deletado.</p>', 'default', array('escape' => false, 'class' => 'notibar msgsuccess'));

            $this->redirect(array('action' => 'index'));
        }
    }

	public function login() {
        if ($this->request->is('post')){
            if ($this->Auth->login()) {
				$this->setPermissions();
                return $this->redirect($this->Auth->redirect());
            } else {
				$this->Session->setFlash(__('Login ou senha estão incorretos'), 'default', array('class' => 'message'), 'auth');
            }    
        }
    }

	public function logout(){
		$this->Session->delete('Auth.Permissions');
		$this->redirect($this->Auth->logout());
	}

    public function crop($id = null){
        if (!$id) {
            throw new NotFoundException(__('Usuário inválido'));
        }

        $usuario = $this->Usuario->findById($id);
        if (!$usuario) {
            throw new NotFoundException(__('usuario'));
        }

		$this->Crop->image_directory = 'files/usuario/photo/' . $usuario["Usuario"]["photo_dir"];
        $this->Crop->quality = 90;
        $this->helpers[]= 'Crop';

        if (empty($this->request->data)) {
            $image = array(
                'original_path' => $usuario["Usuario"]["photo"],
                'append_to_path' => 'thumb_medium',
                'thumb_width' => '400',
                'thumb_height' => '400',
            );

            $this->set('image', $image);
            $this->set('image_directory', $this->Crop->image_directory);
            $this->request->data = $usuario;

        } else {
            foreach($this->request->data['Image'] as $keyImg => $img){
				$fileName = $this->Crop->create_thumb($img); 

				$this->Usuario->id = $id;

				$usuario["Usuario"]["photo"] = $fileName;

				if ($this->Usuario->save($usuario)) {
					$this->Session->setFlash('<a class="close"></a><p>A imagem foi redimensionada.</p>', 'default', array('escape' => false, 'class' => 'notibar msgsuccess'));
					$this->redirect(array('action' => 'view', $this->Usuario->id));
				}
			}
        }
    }

    public function getImage(){
		$this->layout = 'ajax';

		$usuarioId = $this->request->query["usuario_id"];
		$usuario = $this->Usuario->find('first', array('conditions' => array('Usuario.id' => $usuarioId)));
		$this->set('usuarioId', $usuarioId);
	}

    private function setPermissions(){
		$usuario = $this->Auth->user(); 

		$usuarioPerfil = $this->Usuario->Perfil->findById($usuario['perfil_id']);

		$aro = $this->Acl->Aro->find('first', array(
			'conditions' => array(
				'Aro.model' => 'Perfil',
				'Aro.foreign_key' => $usuario['perfil_id'],
			),
		));

		$acos = $this->Acl->Aco->children();
		foreach($acos as $aco){
			$permission = $this->Acl->Aro->Permission->find('first', array(
				'conditions' => array(
					'Permission.aro_id' => $aro['Aro']['id'],
					'Permission.aco_id' => $aco['Aco']['id'],
				),
			));

			if(isset($permission['Permission']['id'])){
				if ($permission['Permission']['_create'] == 1 ||
					$permission['Permission']['_read'] == 1 ||
					$permission['Permission']['_update'] == 1 ||
					$permission['Permission']['_delete'] == 1) {

					$this->Session->write(
						'Auth.Permissions.'.$permission['Aco']['alias'],
						 true
					);
					if(!empty($permission['Aco']['parent_id'])){
						$parentAco = $this->Acl->Aco->find('first', array(
							'conditions' => array(
								'id' => $permission['Aco']['parent_id']
							)	
						));
						$this->Session->write(
							'Auth.Permissions.'.$permission['Aco']['alias']
							.'.'.$parentAco['Aco']['alias'], 
							true
						);
					}
				}
			}
		}
	}
}